package com.mriassl.rabbitmq.unack;

import java.io.IOException;
import java.text.MessageFormat;

import com.mriassl.rabbitmq.base.AbstractConsumer;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Consumer;
import com.rabbitmq.client.DefaultConsumer;
import com.rabbitmq.client.Envelope;

public class UnackHandler01 extends AbstractConsumer{

	private static final String QUEUE_NAME = "UNACK_QUEUE";
	
	public boolean isAck = false;
	
	@Override
	protected void handle() throws Exception {
//		channel.exchangeDeclare(Consts.EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
//		channel.queueDeclare(QUEUE_NAME, false, false, false, null);
//		channel.queueBind(QUEUE_NAME, Consts.EXCHANGE_NAME, Consts.ROUTING_KEY);

		System.out.println(" UnackHandler01 Waiting for messages. To exit press CTRL+C");

		Consumer consumer = new DefaultConsumer(channel) {
			@Override
			public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
				long deliveryTag = envelope.getDeliveryTag();
				System.out.println("============================="+deliveryTag);
				if(isAck) {
				    String message = new String(body, "UTF-8");
				    System.out.println(MessageFormat.format("UnackHandler01 Received RoutingKey:{0},DeliveryTag:{1},Message:{2}", envelope.getRoutingKey(),envelope.getDeliveryTag(),message));
                    getChannel().basicAck(deliveryTag, true);
                }else {
                    getChannel().basicNack(deliveryTag, false, false);
                }
			}
		};
		channel.basicConsume(QUEUE_NAME, false, consumer);
	}
	
	public static void main(String[] args) throws Exception {
	    UnackHandler01 handle = new UnackHandler01();
	    handle.isAck = true;
	    handle.receiveMsg();
    }
	
}
